<script setup lang="ts">
import { onMounted, provide, reactive, ref, toRaw, toRefs, watch } from "vue";
import { getToken } from "@/utils/auth";
import { queryVisualConfigTableData, queryVisualTree, deleteVisualConfigTableData, copyTwinsConfig } from "@/api/visual/visualConfig";
import ConfigPage from "./configPage.vue";
import PhotoUpload from "./components/PhotoUpload.vue";
import { PxMessage, PxMessageBox, PxTree } from "px-ui";
import { cloneDeep } from "@pureadmin/utils";
import { useRouter } from "vue-router";
import TreeV2 from "./components/tree-v2/tree.vue";
import ReTextTooltip from "@/components/ReTextTooltip";
import { eventBus } from "@visual/utils";
const router = useRouter();
defineOptions({
  name: "ALL_VISUAL_CONFIG"
});
const isMain = ref<Boolean>(true);
const isConfig = ref<Boolean>(false);
const facCode = localStorage.getItem("facCode"); //临时处理
const options = [
  {
    value: "BUILD",
    label: "BUILD"
  },
  {
    value: "FAC",
    label: "FAC"
  },
  {
    value: "FLOOR",
    label: "FLOOR"
  },
  {
    value: "ROOM",
    label: "ROOM"
  },
  {
    value: "EQP",
    label: "EQP"
  }
];
const state = reactive<any>({
  queryParams: {
    twinsName: "",
    type: "",
    pageNum: 1,
    pageSize: 30,
    facCode,
    isTemplate: 0
  },
  queryTreeParams: {},
  tableData: [],
  total: 0,

  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  }
});

const { queryParams, tableData, total } = toRefs(state);
// 查询列表
const queryTable = async () => {
  let params = cloneDeep(queryParams.value);
  if (params.isTemplate === 0) delete params.isTemplate;

  const data = await queryVisualConfigTableData(params);
  tableData.value = data?.data;
  total.value = data?.total;
};
onMounted(async () => {
  queryTable();
  await queryAllTree();
  eventBus.on("refreshBaseTree", async () => {
    await queryAllTree();
  });
});

// 重置筛选条件和备件列表
const resetTable = async () => {
  queryParams.value = {
    twinsName: "",
    type: "",
    fullPath: "",
    twinsId: "",
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};
const treeDialogShow = ref(false);
const treeData = ref({});
const editData = ref(null);
const filterText = ref("");
const treeRef = ref<InstanceType<typeof PxTree>>();
const copyRef = ref<InstanceType<typeof PxTree>>();
const selectNode = ref({});
const flettenTree = ref({});
const positionCode = ref("");
provide("curTreeData", flettenTree);
provide("positionCode", positionCode);

const defaultProps = {
  children: "children",
  value: "code",
  label: "name",
  key: "code"
};

const uploadShow = ref(false);
const pictureLists = ref([]);
const picUrl = "/ifp/sharing/api/v1/file/uploadImageFiles";

const isTmpl = ref(false);
const copyDialogShow = ref(false);

watch(filterText, val => {
  treeRef.value!.filter(val);
});

const filterMethod = (query: string, node) => {
  if (query === "hasConfig") {
    return node.hasConfig === false;
  }
  return node.name!.indexOf(query) !== -1 || node.code?.indexOf(query) !== -1 || node.path?.includes(query);
};
//增加一条可视化配置
const addVisual = async tmpl => {
  treeDialogShow.value = true;
  if (tmpl) {
    isTmpl.value = true;
  } else {
    isTmpl.value = false;
  }
  console.log("addVisual--->", treeData);
};
const routerToConfig = pathName => {
  const routerPath = pathName === "tree" ? "/all/visual/tree_config" : "/all/visual/module";
  router.push({
    path: routerPath
  });
};
const routerToDoubleCarbon = () => {
  const routerPath = "/all/visual/double_carbon";
  router.push({
    path: routerPath
  });
};
async function queryAllTree() {
  const lSItem = `visual_index_config_tree_${facCode}`;

  // if (!localStorage.getItem(lSItem)) {
  //   treeData.value = await queryFacPositionTree({ facCode: "FAC_83abf9" });

  //   try {
  //     localStorage.setItem(lSItem, JSON.stringify(treeData.value));
  //   } catch (error) {
  //     console.log(error);
  //   }
  // } else {
  //   try {
  //     treeData.value = JSON.parse(localStorage.getItem(lSItem));
  //   } catch (error) {}
  // }
  treeData.value = await queryVisualTree({ facCode, needEqp: true });
  flettenTree.value = flattenDataByKeys(treeData.value, "code");
  // localStorage.setItem(lSItem, JSON.stringify(treeData.value));
}
function flattenDataByKeys(data, keys) {
  const keyArray = keys.split(" ");

  function recursiveFlatten(obj, result = {}) {
    if (Array.isArray(obj)) {
      obj.forEach(item => recursiveFlatten(item, result));
    } else if (typeof obj === "object" && obj !== null) {
      let hasKey = keyArray.some(key => obj.hasOwnProperty(key));
      let resultKey = keyArray
        .map(key => obj[key])
        .filter(Boolean)
        .join("_");

      if (hasKey && resultKey) {
        result[resultKey] = obj;
      }

      for (let key in obj) {
        recursiveFlatten(obj[key], result);
      }
    }
    return result;
  }

  return recursiveFlatten(data);
}
const treeDialogCofirm = () => {
  treeDialogClosed();
  isMain.value = false;
  isConfig.value = true;
};
const treeDialogClosed = () => {
  treeRef.value.setCurrentKey("");
  treeDialogShow.value = false;
};
const nodeClickHandler = data => {
  selectNode.value = data;
  const { code } = data;
  positionCode.value = code;
};
const copyDialogClosed = () => {
  copyDialogShow.value = false;
};
const copyDialogCofirm = () => {
  copyDialogClosed();
  //
};
const handleCopy = async row => {
  await copyTwinsConfig({ facCode, eqpIds: [row.eqpId] });
  await queryTable();
};
const handleDelete = async row => {
  if (row.id) {
    PxMessageBox.confirm(`要删除当前巡检规则“${row.twinsName}”吗?`, "提示", {
      confirmButtonText: "删除",
      confirmButtonClass: "px-button--danger",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    })
      .then(async () => {
        const res = await deleteVisualConfigTableData({ ids: [row.id] });
        PxMessage.success("删除成功");

        await queryTable();
      })
      .catch(error => {
        console.log(error);
      });
  }
};
const handleEdit = row => {
  editData.value = row;
  const { twinsId } = row;

  positionCode.value = twinsId;
  isMain.value = false;
  isConfig.value = true;
};
const uploadPhotot = () => {
  uploadShow.value = true;
};
const changePhotoList = val => {
  pictureLists.value = val;
};
const uploadPicClose = () => {
  pictureLists.value = [];
};
const keyDown = e => {
  if (e.keyCode == 13 || e.keyCode == 100) {
    queryTable();
  }
};
watch(isMain, newVal => {
  if (newVal) {
    //返回table页面时刷新数据以及重置数据
    queryTable();
    resetData();
  }
});
function resetData() {
  editData.value = null;
}
</script>

<template>
  <div>
    <div v-show="isMain" id="visual-config" class="config-table-common">
      <px-form class="custom-form-ui config-table-form" :model="queryParams" label-position="right" label-width="120px" @submit.prevent="queryTable">
        <px-form-item label="查询可视化列表">
          <px-input
            v-model="queryParams.twinsName"
            placeholder="请输入名称"
            maxlength="50"
            @blur="queryParams.twinsName = $event.target.value.trim()"
          />
        </px-form-item>
        <px-form-item label="查询设备类型">
          <px-select v-model="queryParams.type" placeholder="Select">
            <px-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="是否为模板">
          <px-switch v-model="queryParams.isTemplate" inline-prompt active-text="是" inactive-text="否" :active-value="1" :inactive-value="0" />
        </px-form-item>
        <px-form-item label="路径">
          <px-input
            v-model="queryParams.fullPath"
            placeholder="请输入名称"
            maxlength="50"
            @blur="queryParams.fullPath = $event.target.value.trim()"
          />
        </px-form-item>
        <px-form-item label="孪生体Id">
          <px-input v-model="queryParams.twinsId" placeholder="请输入名称" maxlength="50" @blur="queryParams.twinsId = $event.target.value.trim()" />
        </px-form-item>
        <px-button type="primary" @click="queryTable" @keyup.enter="queryTable">查询</px-button>
        <px-button @click="resetTable">重置</px-button>
      </px-form>
      <div class="visual-config-table-btns mb-[10px]">
        <px-button type="primary" @click="addVisual(false)">新增</px-button>
        <px-button type="primary" @click="addVisual(true)">新增设备模板</px-button>

        <px-button type="primary" plain @click="uploadPhotot">上传图片</px-button>
        <px-button type="primary" @click="routerToConfig('tree')">基础树配置</px-button>
        <px-button type="primary" @click="routerToConfig">组件数据结构配置</px-button>
        <px-button v-has="'ALL_VISUAL_CONFIG_CARBON'" type="primary" @click="routerToDoubleCarbon">双碳</px-button>
      </div>
      <px-table :data="tableData" class="visual-config-table" size="small" height="calc(100vh - 311px)" border>
        <px-table-column prop="twinsName" label="孪生体名称" min-width="240" :resizable="false" show-overflow-tooltip />
        <px-table-column prop="twinsId" label="孪生体Id" min-width="240" :resizable="false" show-overflow-tooltip />
        <px-table-column prop="fullPath" label="完整路径" min-width="240" :resizable="false" show-overflow-tooltip />
        <px-table-column prop="type" label="类型" min-width="240" :resizable="false" show-overflow-tooltip />
        <px-table-column prop="isTemplate" label="是否为模板" min-width="240" :resizable="false" show-overflow-tooltip />
        <px-table-column fixed="right" label="操作" min-width="120" align="center" :resizable="false">
          <template #default="scope">
            <px-tooltip effect="dark" content="编辑" placement="top">
              <px-button link type="primary" @click="handleEdit(scope.row)">
                <px-icon>
                  <EditPen />
                </px-icon>
              </px-button>
            </px-tooltip>
            <px-tooltip effect="dark" content="删除" placement="top">
              <px-button link type="danger" @click="handleDelete(scope.row)">
                <px-icon>
                  <Delete />
                </px-icon>
              </px-button>
            </px-tooltip>
            <px-tooltip v-if="scope.row.isTemplate === 1 && scope.row.type === 'EQP'" effect="dark" content="模板复制" placement="top">
              <px-button link type="primary" @click="handleCopy(scope.row)">
                <px-icon>
                  <Tickets />
                </px-icon>
              </px-button>
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="visual-config-pagination"
        :total="total"
        @pagination="queryTable"
      />
      <px-dialog v-model="treeDialogShow" title="请选择创建的区域" width="30%" align-center @closed="treeDialogClosed">
        <div class="subject-tree-content">
          <px-input v-model="filterText" clearable placeholder="请填写名称" />
          <px-scrollbar height="300px">
            <px-tree-v2
              ref="treeRef"
              :height="300"
              highlight-current
              :expand-on-click-node="false"
              node-key="id"
              :data="treeData"
              :props="defaultProps"
              :filter-method="filterMethod"
              @node-click="nodeClickHandler"
            >
              <template #default="{ data }">
                <div class="w-[250px]" :class="{ isNoConfg: data.hasConfig === false }">
                  <ReTextTooltip :content="data.type !== 'EQP' ? data.name : `${data.code}/${data.name}`" />
                </div>
              </template>
            </px-tree-v2>
          </px-scrollbar>
          <px-checkbox v-model="isTmpl" label="设定为模板" size="large" disabled />
        </div>
        <template #footer>
          <span class="dialog-footer">
            <px-button @click="treeDialogClosed">取消</px-button>
            <px-button type="primary" @click="queryAllTree"> 刷新数据 </px-button>

            <px-button type="primary" @click="treeDialogCofirm"> 确定 </px-button>
          </span>
        </template>
      </px-dialog>
      <px-dialog v-model="copyDialogShow" title="请选择复制的设备" width="30%" align-center @closed="copyDialogClosed">
        <div class="subject-tree-content">
          <px-input v-model="filterText" clearable placeholder="请填写名称" />
          <px-scrollbar height="300px">
            <tree-v2
              ref="copyRef"
              :height="300"
              highlight-current
              :expand-on-click-node="false"
              node-key="id"
              show-checkbox
              :data="treeData"
              :props="defaultProps"
              :filter-method="filterMethod"
              @node-click="nodeClickHandler"
            />
          </px-scrollbar>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <px-button @click="copyDialogClosed">取消</px-button>
            <px-button type="primary" @click="copyDialogCofirm"> 确定 </px-button>
          </span>
        </template>
      </px-dialog>
    </div>
    <ConfigPage
      v-model:select-node="selectNode"
      v-model:is-tmpl="isTmpl"
      v-model:is-main="isMain"
      v-model:is-config="isConfig"
      :edit-data="editData"
    />
    <px-dialog v-model="uploadShow" title="请选择上传图片" width="30%" align-center @close="uploadPicClose">
      <PhotoUpload
        v-if="uploadShow"
        photoType="add"
        :actionUrl="picUrl"
        :photoData="{ moduleName: 'twins_visualization' }"
        :photoList="pictureLists"
        @changePhotoList="changePhotoList"
      />
    </px-dialog>
  </div>
</template>

<style lang="scss" scoped>
@import url("./scss/config-table.scss");

.subject-tree-content {
  box-sizing: border-box;
  padding: 24px;
  border: 1px solid #dfdfdf;
  border-radius: 4px;

  .isNoConfg {
    color: red;
  }

  .px-scrollbar {
    box-sizing: border-box;
    padding-right: 12px;
    margin-top: 16px;

    :deep(.px-tree-node) {
      & > .px-tree-node__children {
        overflow: visible;
      }
    }
  }
}
</style>
